package cn.smile.interceptor.home;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import com.alibaba.fastjson.JSON;
import cn.smile.bean.CodeMsg;
import cn.smile.constant.SessionConstant;
import cn.smile.util.StringUtil;

/**
 * 前台登录拦截器
 */
@Slf4j
@Component
public class HomeLoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        String requestURI = request.getRequestURI();
        HttpSession session = request.getSession();
        Object attribute = session.getAttribute(SessionConstant.SESSION_STUDENT_LOGIN_KEY);
        if (attribute == null) {
            log.info("学生还未登录或者session失效,重定向到登录页面,当前URL= {}", requestURI);
            //首先判断是否是ajax请求
            if (StringUtil.isAjax(request)) {
                //表示是ajax请求
                try {
                    response.setCharacterEncoding("UTF-8");
                    response.getWriter().write(JSON.toJSONString(CodeMsg.USER_SESSION_EXPIRED));
                } catch (IOException e) {
                    log.error("写入session异常, e: ", e);
                }
                return false;
            }
            //说明是普通请求，可直接重定向到登录页面
            //用户还未登录或者session失效,重定向到登录页面
            try {
                response.sendRedirect("/home/index/login");
            } catch (IOException e) {
                log.error("重定向登录页异常, e: ", e);
            }
            return false;
        }
        log.info("该请求符合前台登录要求，放行 {}", requestURI);
        return true;
    }
}
